package com.wbq.datastructuredemo.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import com.wbq.datastructuredemo.R;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;

public class CartoonActivity extends Activity {
	// 文件的路径
	public final static String URL = "/data/data/com.wbq.datastructuredemo/files";
	// 数据库文件
	public final static String DB_FILE_NAME = "javamanual.db";
	// 表名
	public final static String TABLE_NAME = "java_basic";
	private static final String TAG = "CartoonActivity";

	SQLiteDatabase db = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 设置窗口没有标题
		setContentView(R.layout.activity_cartoon);
		// 首先将DB文件拷贝至程序内存当中
		// 注解1
		if (copyDB()) {
			// 得到数据库文件
			File file = new File(URL, DB_FILE_NAME);
			db = SQLiteDatabase.openOrCreateDatabase(file, null);
			Log.i(TAG, "打开数据库成功");
			Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null);
			cursor.moveToFirst();
			while (cursor.moveToNext()){
				//获取号码省级与市级归属地
				String text = cursor.getString(0) + cursor.getString(1) +cursor.getString(2) + cursor.getString(3);
				Log.i(TAG, text);
			}
		}
	}

	// 将raw文件中的数据库文件拷贝至手机中的程序内存当中
	public boolean copyDB() {

		try {
			// 判断程序内存中是否有拷贝后的文件
			if (!(new File(URL+"//javamanual.db")).exists()) {
				InputStream is = getResources().openRawResource(
						R.raw.javamanual);
				getApplicationContext();
				FileOutputStream fos = CartoonActivity.this.openFileOutput(DB_FILE_NAME,
						Context.MODE_PRIVATE);
				// 一次拷贝的缓冲大小1M
				byte[] buffer = new byte[1024 * 1024];
				int count = 0;
				// 循环拷贝数据库文件
				while ((count = is.read(buffer)) > 0) {
					fos.write(buffer, 0, count);
				}
				Log.i(TAG, "复制数据库成功");
				fos.close();
				is.close();
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			Log.i(TAG, "复制数据库失败");
			return false;
		}
	}

}
